package com.nerve.cloudoffice.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.nerve.util.FormatUtil;

import com.nerve.cloudoffice.common.SessionUtil;
import com.nerve.cloudoffice.domain.Task;
import com.nerve.cloudoffice.domain.TrashApply;
import com.nerve.cloudoffice.domain.User;
import com.nerve.cloudoffice.domain.dao.TaskDao;
import com.nerve.cloudoffice.domain.dao.TrashApplyDao;
import com.nerve.cloudoffice.domain.dao.UserDao;
import com.nerve.cloudoffice.service.ServiceExceptions;
import com.nerve.cloudoffice.service.TaskService;
import com.nerve.cloudoffice.web.model.TaskModel;

/**
 * @project: cloudOffice
 * @file: TaskServiceImpl.java
 * @package: com.nerve.cloudoffice.service.impl
 * @description:
 *
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: 2013-8-4
 * @change log:
 */
public final class TaskServiceImpl implements TaskService {
	
	public static final int ACCEPT = 0;
	public static final int REJECT = 1;
	public static final int REDIRECT = 2;

	private TaskDao dao;
	private TrashApplyDao trashDao;
	private UserDao userDao;
	
	private TaskDao getDao(){
		if(dao == null)
			dao = new TaskDao();
		
		return dao;
	}
	
	private TrashApplyDao getTrashDao(){
		if(trashDao == null)
			trashDao = new TrashApplyDao();
		
		return trashDao;
	}
	
	private UserDao getUserDao(){
		if(userDao == null)
			userDao = new UserDao();
		
		return userDao;
	}
	
	/**
	 * 局部更新一个任务
	 */
	public void updateTask(TaskModel model) throws Exception {
		Task task = getDao().getById(model.getId());
		FormatUtil.notNull(task, "找不到指定的Task对象，id=" + model.getId());
		
		User u = SessionUtil.getLoginUser();
		FormatUtil.notNull(u, ServiceExceptions.NO_LOGIN);
		
		int value;
		switch (model.getUpdateType()) {
		case STATUS:
			value = Integer.valueOf(model.getUpdateValue());
			if(value < 0)
				value = 0;
			if(value > 100)
				value = 100;
			
			task.setStatus(value);
			break;

		case LEVEL:
			value = Integer.valueOf(model.getUpdateValue());
			task.setLevel(value);
			break;
			
		/*
		 * 申请删除一个任务	
		 */
		case TRASH:
			TrashApply apply = new TrashApply();
			apply.setJoinDate(new Date());
			apply.setSender(u);
			apply.setTask(task);
		
			getTrashDao().save(apply);
			return ;
			
		case MESSAGE:
			String message = new String(model.getUpdateValue().getBytes("ISO-8859-1"),"utf-8");
			task.setMessage(message);
			break;
		}
		
		getDao().merge(task);
	}
	
	
	/**
	 * model中的workerId 就是职员id
	 * id 就是部门id，这里为了节约属性的个数哈
	 */
	public void list(TaskModel model) throws Exception {
		StringBuilder hql = new StringBuilder("FROM Task as t WHERE 1=1");
		
		if(model.getWorkerId() > 0){
			hql.append(" and worker_id=" + model.getWorkerId());
		}else if(model.getId() > 0){
			hql.append(" and t.workUser.id in (select w.id from User as w where w.department.id="+model.getId()+")");
		}
		
		//String[] ranges = buildDate(model.getRange());
		//hql.append(" and (t.endDate >'" +ranges[0]+ "' and t.endDate< '"+ranges[1]+"' )");
		
		int days[] = new int[2];
		if(model.getRange() == null)
			model.setRange(TODAY);
		if(model.getRange().equals(TODAY)){
			days[0] = 0;
			days[1] = 1;
		}
		else if(model.getRange().equals(WEEK)){
			days[0] = 1;
			days[1] = 7;
		}
		else if(model.getRange().equals(MONTH)){
			days[0] = 7;
			days[1] = 30;
		}
		else if(model.getRange().equals(YEAR)){
			days[0] = 30;
			days[1] = 365;
		}
		
		
		hql.append(" and (DATEDIFF(t.endDate, t.startDate) >= "
				+days[0]+" and DATEDIFF(t.endDate, t.startDate) < "+days[1]+")");
		
		model.setTotalCount(getDao().countRow(hql.toString()));
		List<Task> list = getDao().getList(hql.toString(), model.getPage(), model.getPageSize());
		model.setTaskList(list);
	}
	
	private String[] buildDate(String range){
		if(range == null)
			range = TODAY;
		String[] result = new String[2];
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE,0);
		c.set(Calendar.SECOND, 1);
		
		if(range.equals(TODAY)){
			result[0] = df.format(c.getTime());
			
			c.add(Calendar.DAY_OF_YEAR, 1);
			result[1] = df.format(c.getTime());
		}else{
			c.add(Calendar.DAY_OF_WEEK, 0);
			result[0] = df.format(c.getTime());
			
			c.add(Calendar.DAY_OF_WEEK, 6);
			c.set(Calendar.HOUR_OF_DAY, 23);
			result[1] = df.format(c.getTime());
		}
		
		return result;
	}

	public void save(TaskModel model) throws Exception {
		Task task = model.getTask();
		
		FormatUtil.notNull(task, "填写的参数有误！");
		FormatUtil.notNull(task.getTitle(), "任务标题不能为空！");
		FormatUtil.notNull(task.getStartDate(), "任务开始时间不能为空！");
		
		User worker = getUserDao().getById(model.getWorkerId());
		FormatUtil.notNull(worker, "任务执行者必须填写！");
		task.setWorkUser(worker);
		
		User user = SessionUtil.getLoginUser();
		task.setSendUser(user);
		
		if(task.getStatus() < 0)
			task.setStatus(0);
		if(task.getStatus() > 100)
			task.setStatus(100);
		
		if(task.getId()!=null && task.getId() > 0)
			getDao().merge(task);
		else
			getDao().save(task);
	}

	/**
	 * 将一个任务的trash属性，变成1
	 */
	public void trash(TaskModel model) throws Exception {
		User u = SessionUtil.getLoginUser();
		
		getTrashDao().pass(u, model.getId());
	}

	public void updateBatch(TaskModel model) throws Exception {
		Task task = model.getTask();
		
		if(task.getId() > 0){
			Task temp = getDao().getById(task.getId());
			
			temp.setStatus(task.getStatus());
			temp.setLevel(task.getLevel());
			temp.setMessage(task.getMessage());
			
			getDao().merge(temp);
		}
	}

	/**
	 * 列出删除申请
	 * 如果登录的是部门主管，只能看到本部门的
	 * 如果是总主管，那么可以看到全部的
	 * 如果是普通职员，提示权限不够
	 */
	public void listTrash(TaskModel model) throws Exception {
		User u = SessionUtil.getLoginUser();
		if(u.getPosition() == User.EMPLOYEE){
			throw new Exception("你没有权限查看删除申请");
		}
		
		StringBuilder hql = new StringBuilder("FROM TrashApply as t WHERE 1=1");
		if(u.getPosition() == User.HEAD_OF_DEPARTMENT){
			int did = u.getDepartment().getId();
			
			hql.append(" and t.sender.department.id=" + did);
		}
		
		hql.append(" order by joinDate desc");
		
		model.setTotalCount(getTrashDao().countRow(hql.toString()));
		List<TrashApply> list = getTrashDao().getList(hql.toString(), 1, 100);
		model.setTrashList(list);
	}

	public void accept(TaskModel model) throws Exception {
		User user = SessionUtil.getLoginUser();
		
		Task task = getDao().getById(model.getId());
		if(!task.getWorkUser().getId().equals(user.getId()))
			throw new Exception("你不能操作执行者不是你的任务");
		
		if(model.getUpdateType() == ACCEPT){
			task.setLoaction(Task.ACCEPTED);
		}else if(model.getUpdateType() == REJECT){
			task.setLoaction(Task.REJECT);
		}else if(model.getUpdateType() == REDIRECT){
			int workid = Integer.valueOf(model.getUpdateValue());
			
			User worker = getUserDao().getById(workid);
			if(worker == null)
				throw new Exception("新委派的任务执行者无效");
			
			task.setLoaction(Task.WAIT_ACCEPT);
			task.setWorkUser(worker);
		}
		
		getDao().merge(task);
	}
}